package com.itheima.health.utils;

import java.util.*;

/**
 * 一个获取各年龄段个数count的工具类
 */
public class IdCardUtils {
    public static int getAge(String idCard) {
        String year = "";
        if (idCard.length() == 15) {
            String century = "19";
            String substring = idCard.substring(6, 8);
            if (substring.equals("00")) {
                century = "20";
            }

            // 对应的17位的各个系数
            int[] weight = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10,
                    5, 8, 4, 2};

            // 通过加入世纪码, 变成 17 位的新号码本体.
            String tempNo = idCard.substring(0, 6) + century
                    + idCard.substring(6);

            // 下面算最后一位校验码
            int checkSum = 0;
            for (int i = 0; i < weight.length; i++) {
                int ai = Integer.parseInt("" + tempNo.charAt(i)); // 位于 i 位置的数值
                checkSum = checkSum + ai * weight[i];
            }
            // 求余数
            int checkNum = checkSum % 11;
            String lastNumber = null;
            switch (checkNum) {
                case 0:
                    lastNumber = "1";
                    break;
                case 1:
                    lastNumber = "0";
                    break;
                case 2:
                    lastNumber = "X";
                    break;
                case 3:
                    lastNumber = "9";
                    break;
                case 4:
                    lastNumber = "8";
                    break;
                case 5:
                    lastNumber = "7";
                    break;
                case 6:
                    lastNumber = "6";
                    break;
                case 7:
                    lastNumber = "5";
                    break;
                case 8:
                    lastNumber = "4";
                    break;
                case 9:
                    lastNumber = "3";
                    break;
                case 10:
                    lastNumber = "2";
                    break;
            }
            idCard = tempNo + lastNumber;
        }

        year = idCard.substring(6, 10);
        // 当前年份
        Calendar instance = Calendar.getInstance();
        int currentYear = instance.get(Calendar.YEAR);
        int age = currentYear - Integer.parseInt(year) + 1;
        return age;

    }
}
